package com.ky.tms.service.impl;

import com.aliyun.oss.OSS;
import com.ky.tms.service.IOssService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@Service
public class OssServiceImpl implements IOssService {

    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".svg", ".gif", ".png"};

    @Autowired
    private OSS ossClient;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Override
    public String uploadImg(MultipartFile uploadFile) throws Exception {
        String filePath = null;
        try{
            // 校验文件格式
            boolean isLegal = false;
            for (String type : IMAGE_TYPE) {
                if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                    isLegal = true;
                    break;
                }
            }
            if (!isLegal) {
                throw new Exception("图片格式不正确");
            }
            filePath = getFilePath("xinxin-images/",uploadFile.getOriginalFilename());
            ossClient.putObject(bucketName,filePath, uploadFile.getInputStream());
        } catch (Exception e){
            e.printStackTrace();
            throw e;
        }
        return filePath;
    }

    /**
     * 生成路径以及文件名 例如：//digitalmirror/2019/04/28/15564277465972939.jpg
     *
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String ossDir, String sourceFileName) {
        LocalDateTime now = LocalDateTime.now();
        return ossDir + now.getYear()
                + "/" + now.getMonthValue() + "/"
                + now.getDayOfMonth() + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

}
